package main

import (
	"fmt"
	"os"
	"reflect"
	"runtime"
	"strings"
	"ttbot_vx/modules/control"
	"ttbot_vx/modules/fun"
	"ttbot_vx/shared/utils"

	"github.com/eatmoreapple/openwechat"
	"github.com/skip2/go-qrcode"
)

func main() {
	bot := openwechat.DefaultBot(openwechat.Desktop) // 桌面模式

	// 注册控制模块
	dispatcher := openwechat.NewMessageMatchDispatcher()
	for _, module := range control.ModuleList {
		dispatcher.RegisterHandler(module.Match, module.Handler)

		handlerValue := reflect.ValueOf(module).FieldByName("Handler")
		splitRes := strings.Split(runtime.FuncForPC(handlerValue.Pointer()).Name(), "/")
		wholeName := strings.Split(splitRes[len(splitRes)-1], ".")

		utils.Logger.Printf("[%v] <%v> 加载成功.", strings.ToUpper(wholeName[0]), wholeName[1])
	}
	// 注册娱乐模块
	for _, module := range fun.ModuleList {
		dispatcher.RegisterHandler(module.Match, module.Handler)

		handlerValue := reflect.ValueOf(module).FieldByName("Handler")
		splitRes := strings.Split(runtime.FuncForPC(handlerValue.Pointer()).Name(), "/")
		wholeName := strings.Split(splitRes[len(splitRes)-1], ".")

		utils.Logger.Printf("[%v] <%v> 加载成功.", strings.ToUpper(wholeName[0]), wholeName[1])
	}
	bot.MessageHandler = dispatcher.AsMessageHandler()

	// 注册心跳回调函数（不注册则是隔一段时间在console上打印一行状态）
	bot.SyncCheckCallback = func(resp openwechat.SyncCheckResponse) {
	}

	// 注册登陆二维码回调
	bot.UUIDCallback = ConsoleQrCode

	// 创建 ./data/cache 文件夹以保存登录缓存
	err := os.MkdirAll("./data/cache", 0777)
	if err != nil {
		fmt.Println(err)
		return
	}

	mode := work
	if mode == debug {
		// 热登录
		reloadStorage := openwechat.NewFileHotReloadStorage("./data/cache/storage_hot_login.json")
		defer reloadStorage.Close()
		if err := bot.HotLogin(reloadStorage, openwechat.NewRetryLoginOption()); err != nil {
			fmt.Println(err)
			return
		}
	} else if mode == work {
		// 推送登陆（手机端点确定）
		reloadStorage := openwechat.NewFileHotReloadStorage("./data/cache/storage_push_login.json")
		defer reloadStorage.Close()
		if err := bot.PushLogin(reloadStorage, openwechat.NewRetryLoginOption()); err != nil {
			fmt.Println(err)
			return
		}
	}

	// 阻塞主goroutine, 直到发生异常或者用户主动退出
	bot.Block()
}

func ConsoleQrCode(uuid string) {
	q, _ := qrcode.New("https://login.weixin.qq.com/l/"+uuid, qrcode.Low)
	fmt.Println(q.ToString(true))
}

const debug = 114514
const work = 666
